#api是什么？

#api    设计      功能
#请求路由   请求方法     接收参数  参数类型    返回数据    状态码
#/student   GET         无       无           json    0表示成功   111数据库错误  222表示数据为0
#restful  --接口规范，接口设计风格
#restful -- 表现层状态转移

#非restful接口架构
#/stuent/add    post,put
#/stuent/modify    post,put
#/student/delete
#/student/get


#restful接口架构
#将每一类数据看作一类资源
#资源通过http的动作来实现状态转移 GET,PUT,POST,DELETE

#/{version}/resource/resource_id}
#version:API版本号,有些版本号放置在头信息，通过控制版本号有利于应用迭代
#resource:资源
#resource_id:资源的id，某一个具体的对象实例

#restful api 设计
                # 方法
#/v1/student    POST    新增
#               GET     查询所有学生
#/v1/student/1  PUT     修改
#               DELETE  删除学生信息
#               GET     查询某一个学生的具体信息

#怎么写

from . import stu_bp
from flask_restful import Api,Resource
from lib.resp import responseFunc
from lib.connect_mysql import connect_mysql
from flask import request
from model import con

#将restful api对象和蓝图绑定
api = Api(stu_bp)
class Student(Resource):
    def get(self,id=None):
        with con.cursor() as cursor:
            if id is not None:
                sql = "select * from student where stuId=%s"
                cursor.execute(sql,id)
                con.commit()
                return responseFunc(cursor.fetchone())

            else:
                sql = "select * from student"
                cursor.execute(sql)
                con.commit()
                return responseFunc(cursor.fetchall())
    def post(self):



        #先接收客户端的输入  json    request.json
        #将数据存入数据库
        #   连接数据库   在程序运行之初就需要建立连接
        try:

            stuName = request.json.get("stuName")
            stuAge = request.json.get("stuAge")
            stuAddress = request.json.get("stuAddress")
            stuSex = request.json.get("stuSex")

            with con.cursor() as cursor:
                insert_sql = (f"INSERT INTO student(stuName, stuAge, stuAddress, stuSex) VALUES(%s, %s, %s, %s) ")
                print(insert_sql)
                cursor.execute(insert_sql,(stuName,stuAge,stuSex,stuAddress))
                con.commit()

            return responseFunc(message="this is post func")
        except Exception as e:
            print("插入失败")
    def put(self,id):
        try:
            with con.cursor() as cursor:
                stuName = request.json.get("stuName")
                stuAge = request.json.get("stuAge")
                stuAddress = request.json.get("stuAddress")
                stuSex = request.json.get("stuSex")
                sql_update = "update student set stuName = %s,stuAge = %s,stuAddress = %s,stuSex = %s where stuId = %s"


                # update student set stuName = "ggww",stuAge = 92,stuAddress = "we",stuSex = "eee" where stuId = 1;
                cursor.execute(sql_update,(stuName,stuAge,stuAddress,stuSex,id))
                print("修改成功")
                con.commit()
                return responseFunc(message="this is put func")
        except Exception as e:
            con.rollback()
            print("修改失败，数据回滚")
    def delete(self,id):
        try:
            with con.cursor() as cursor:
                stuName = request.json.get("stuName")
                stuAge = request.json.get("stuAge")
                stuAddress = request.json.get("stuAddress")
                stuSex = request.json.get("stuSex")
                sql_delete = "delete from student where stuId = %s"
                cursor.execute(sql_delete,(id))
                connect_mysql().commit()
                print("删除成功")

            return responseFunc(message="this is delete func")
        except Exception as e:
            con.rollback()
            print("删除失败，数据回滚")
#接收两种url传输方式
api.add_resource(Student,'/student')

#避免endpoint重复，endpoint全局唯一
api.add_resource(Student,'/student/<int:id>',endpoint='studentid')




# from . import stu_bp
# from flask_restful import Api, Resource
# from lib.resp import responseFunc
# from lib.connect_mysql import pymysql
# from flask import request
#
# # 数据库配置
# DB_CONFIG = {
#     'host': '192.168.248.133',
#     'user': 'flask',
#     'password': '@0713NBwq',
#     'database': 'sqjxflask',
#     'charset': 'utf8',
#     'port': 3308,
#     'cursorclass': pymysql.cursors.DictCursor
# }
#
#
# def create_connection():
#     """创建数据库连接"""
#     try:
#         return pymysql.connect(**DB_CONFIG)
#     except Exception as e:
#         print(f"数据库连接失败: {e}")
#         return None
#
#
# api = Api(stu_bp)
#
#
# class Student(Resource):
#     # GET: 查询单个或所有学生
#     def get(self, id=None):
#         connection = create_connection()
#         if not connection:
#             return responseFunc(message="数据库连接失败", code=500)
#
#         try:
#             with connection.cursor() as cursor:
#                 if id:
#                     # 查询单个学生
#                     sql = "SELECT * FROM student WHERE id = %s"
#                     cursor.execute(sql, (id,))
#                     result = cursor.fetchone()
#                     if result:
#                         return responseFunc(data=result, message="查询成功")
#                     else:
#                         return responseFunc(message=f"未找到ID为{id}的学生", code=404)
#                 else:
#                     # 查询所有学生
#                     sql = "SELECT * FROM student"
#                     cursor.execute(sql)
#                     result = cursor.fetchall()
#                     return responseFunc(data=result, message="查询成功")
#
#         except Exception as e:
#             return responseFunc(message=f"查询失败: {str(e)}", code=500)
#
#         finally:
#             if connection:
#                 connection.close()
#
#     # POST: 新增学生
#     def post(self):
#         connection = create_connection()
#         if not connection:
#             return responseFunc(message="数据库连接失败", code=500)
#
#         try:
#             data = request.json
#             # 验证必填字段
#             required = ["stuName", "stuAge", "stuSex"]
#             if not all(field in data for field in required):
#                 return responseFunc(message="姓名、年龄、性别为必填项", code=400)
#
#             sql = """
#                   INSERT INTO student(stuName, stuAge, stuAddress, stuSex)
#                   VALUES (%s, %s, %s, %s) \
#                   """
#             with connection.cursor() as cursor:
#                 cursor.execute(sql, (
#                     data["stuName"],
#                     data["stuAge"],
#                     data.get("stuAddress", ""),  # 可选字段，默认为空
#                     data["stuSex"]
#                 ))
#                 connection.commit()
#                 return responseFunc(message="学生信息添加成功", code=201)
#
#         except Exception as e:
#             connection.rollback()
#             return responseFunc(message=f"添加失败: {str(e)}", code=500)
#
#         finally:
#             if connection:
#                 connection.close()
#
#     # PUT: 更新学生信息
#     def put(self, id):
#         connection = create_connection()
#         if not connection:
#             return responseFunc(message="数据库连接失败", code=500)
#
#         try:
#             data = request.json
#             if not data:
#                 return responseFunc(message="请提供更新的数据", code=400)
#
#             with connection.cursor() as cursor:
#                 # 检查学生是否存在
#                 cursor.execute("SELECT * FROM student WHERE id = %s", (id,))
#                 if not cursor.fetchone():
#                     return responseFunc(message=f"未找到ID为{id}的学生", code=404)
#
#                 # 构建更新字段
#                 update_fields = []
#                 params = []
#                 for key, value in data.items():
#                     if key in ["stuName", "stuAge", "stuAddress", "stuSex"]:
#                         update_fields.append(f"{key} = %s")
#                         params.append(value)
#
#                 if not update_fields:
#                     return responseFunc(message="没有有效的更新字段", code=400)
#
#                 # 执行更新
#                 sql = f"UPDATE student SET {', '.join(update_fields)} WHERE id = %s"
#                 params.append(id)
#                 cursor.execute(sql, params)
#                 connection.commit()
#                 return responseFunc(message=f"ID为{id}的学生信息已更新")
#
#         except Exception as e:
#             connection.rollback()
#             return responseFunc(message=f"更新失败: {str(e)}", code=500)
#
#         finally:
#             if connection:
#                 connection.close()
#
#     # DELETE: 支持单条删除和批量删除
#     def delete(self, id=None):
#         connection = create_connection()
#         if not connection:
#             return responseFunc(message="数据库连接失败", code=500)
#
#         try:
#             with connection.cursor() as cursor:
#                 if id:
#                     # 单条删除：通过URL路径参数
#                     cursor.execute("SELECT * FROM student WHERE id = %s", (id,))
#                     if not cursor.fetchone():
#                         return responseFunc(message=f"未找到ID为{id}的学生", code=404)
#
#                     cursor.execute("DELETE FROM student WHERE id = %s", (id,))
#                     connection.commit()
#                     return responseFunc(message=f"ID为{id}的学生已删除")
#
#                 else:
#                     # 批量删除：通过JSON传递ids列表
#                     data = request.json
#                     if not data or "ids" not in data or not isinstance(data["ids"], list):
#                         return responseFunc(
#                             message="请通过JSON提供要删除的id列表，格式: {\"ids\": [1,2,3]}",
#                             code=400
#                         )
#
#                     # 检查ids是否存在
#                     placeholders = ", ".join(["%s"] * len(data["ids"]))
#                     cursor.execute(f"SELECT id FROM student WHERE id IN ({placeholders})", data["ids"])
#                     existing_ids = [row["id"] for row in cursor.fetchall()]
#
#                     if not existing_ids:
#                         return responseFunc(message="没有找到要删除的学生数据", code=404)
#
#                     # 执行批量删除
#                     cursor.execute(f"DELETE FROM student WHERE id IN ({placeholders})", data["ids"])
#                     connection.commit()
#                     return responseFunc(
#                         message=f"成功删除{len(existing_ids)}条学生数据",
#                         data={"deleted_ids": existing_ids}
#                     )
#
#         except Exception as e:
#             connection.rollback()
#             return responseFunc(message=f"删除失败: {str(e)}", code=500)
#
#         finally:
#             if connection:
#                 connection.close()
#
#
# # 注册路由
# api.add_resource(Student, '/student')
# api.add_resource(Student, '/student/<int:id>', endpoint='studentid')

# #对数据进行操作
#CREATE TABLE student(
    # ->     stuId INT PRIMARY KEY AUTO_INCREMENT,
    # ->     stuName VARCHAR(50) NOT NULL,
    # ->     stuAge INT NOT NULL,
    # ->     stuAddress VARCHAR(50) NOT NULL,
    # ->     stuSex VARCHAR(50)
    # -> ) CHARSET=utf8;
